package com.tang.web_standard.global.response.handler;

import com.tang.web_standard.global.response.Result;
import com.tang.web_standard.global.response.ResultBuilder;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * @Author tangyuan2meicloud.com
 * @DATE 2021/9/16 19:49
 * @Desc
 * @Remarks
 */
@Slf4j
public class ResponseBodyWrapper implements HandlerMethodReturnValueHandler {

    private static final Logger _logger = LoggerFactory.getLogger(ResponseBodyWrapper.class);

    private final HandlerMethodReturnValueHandler handler;

    public ResponseBodyWrapper(HandlerMethodReturnValueHandler handler) {
        this.handler = handler;
    }

    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        return handler.supportsReturnType(returnType);
    }


    @Override
    public void handleReturnValue(Object returnValue,
                                  MethodParameter returnType, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest) throws Exception {
        _logger.info("return data is " + returnValue);
        if (returnValue instanceof Void) {
            returnValue = ResultBuilder.DEFAULT_RESULT;
        } else {
            if (!(returnValue instanceof Result)) {
                returnValue = ResultBuilder.ok(returnValue);
            }
        }
        handler.handleReturnValue(returnValue, returnType, mavContainer, webRequest);
    }

}